package de.karlNet.gifSocket.servlets;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import de.karlNet.gifSocket.controllers.SessionController;
import de.karlNet.gifSocket.controllers.interfaces.ISessionController;

@Controller
@RequestMapping("/upload")
public class UploadServlet  {
	private static final long serialVersionUID = 1L;
	@Autowired
	private ISessionController sessionController;


	@RequestMapping(value = "", method = RequestMethod.POST)
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ServletFileUpload upload = new ServletFileUpload();
		System.out.println("next image server");
		Integer sessionId = Integer
				.parseInt(request.getParameter("session_id"));
		// Parse the request
		FileItemIterator iter;
		try {
			iter = upload.getItemIterator(request);
			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				InputStream stream = item.openStream();
				if (!item.isFormField()) {
					InputStream imageStream = stream;
					BufferedImage imageToAdd = ImageIO.read(imageStream);
					sessionController
							.addPictureToSession(sessionId, imageToAdd);
					// Process the input stream
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

}
